#include <iostream>
#include <unistd.h>
#include <cstdlib>
#include <ctime>
#include <assert.h>
#include <vector>
#include <sys/wait.h>
#include <sys/types.h>
#include "Task.hpp"

using namespace std;

#define PROCESS_NUM 5

int waitCommand(int waitFd, bool& quit)
{
    uint32_t command = 0;
    ssize_t s = read(waitFd, &command, sizeof(command));
    if (s == 0)
    {
        quit = true;
        return -1;
    }
    assert(s == sizeof(uint32_t));
    return command;
}

void sendAndWeakUp(pid_t who, int fd, uint32_t command)
{
    write(fd, &command, sizeof(command));
    cout << "call process " << who << "execute" << desc[command] << " through " << fd << endl;
}

int main()
{
    load();
    vector<pair<pid_t, int>> slots;
    //创建多个进程
    for (int i = 0; i < PROCESS_NUM; i++)
    {
        //创建管道
        int pipefd[2] = {0};
        int n = pipe(pipefd);
        assert(n == 0);
        (void)n;

        pid_t id = fork();
        assert(id != -1);
        //子进程进行读取
        if (id == 0)
        {
            //子进程
            //关闭写端
            close(pipefd[1]);
            while (true)
            {
                //等命令
                bool quit = false;
                int command = waitCommand(pipefd[0], quit);//不发命令就阻塞
                if (quit) break;
                //执行命令
                if (command >= 0 && command < handlerSize())
                {
                    callbacks[command]();
                }
                else
                {
                    cout << "非法command:" << command << endl;
                }
            }
            exit(1);
        }
        //父进程
        //关闭读端
        close(pipefd[0]);
        slots.push_back(pair<pid_t, int>(id, pipefd[1]));
    }
    //父进程派发任务
    srand((unsigned long)time(nullptr) ^ getpid() ^ 23323123123L);//更随机
    while (true)
    {
        int select;
        int command;
        cout << "#########################################" << endl;
        cout << "#   1.show functions   2.send command   #" << endl;
        cout << "#########################################" << endl;
        cout << "Please Select: ";
        cin >> select;
        if (select == 1) showHandler();
        else if (select == 2)
        {
            cout << "Enter Your Command: ";
            //选择任务
            cin >> command;
            //选择进程
            int choice = rand() % slots.size();
            //把任务给指定的进程
            sendAndWeakUp(slots[choice].first, slo  ts[choice].second, command);
        }
        else
        {

        }

    }

    //关闭fd, 结束所有进程
    for (const auto& slot : slots)
    {
        close(slot.second);
    }

    for (const auto& slot : slots)
    {
        waitpid(slot.first, nullptr, 0);
    }
    close(pipefd[1]);
    return 0;
}
